﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace yafc.UI.Components
{
	public partial class AutoSizeBox : TextBox
	{
		public bool VerticalSpread
		{
			get
			{
				if ((Anchor | AnchorStyles.Left) != 0 && (Anchor | AnchorStyles.Right) != 0)
					if (Multiline)
						return true;
				return false;
			}
			set
			{
				if (value)
				{
					Anchor = AnchorStyles.Left | AnchorStyles.Right;
					Multiline = true;
				}
				else
				{
					Anchor |= ~AnchorStyles.Left;
					Anchor |= ~AnchorStyles.Right;
					Multiline = false;
				}
			}
		}

		public AutoSizeBox()
		{
			InitializeComponent();
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			base.OnPaint(e);
		}
		protected override void OnLayout(LayoutEventArgs levent)
		{
			base.OnLayout(levent);

			using (var g = CreateGraphics())
			{
				if (VerticalSpread)
				{
					int textwidth = ClientSize.Width - Padding.Right - Padding.Left;
					var preferredSize = g.MeasureString(Text, Font, textwidth).ToSize();

					if (preferredSize.Height < MinimumSize.Height)
					{
						preferredSize.Height = MinimumSize.Height;
						if (preferredSize.Height == 0)
						{
							preferredSize.Height = Font.Height;
						}
					}
					ClientSize = new Size(ClientSize.Width,
						preferredSize.Height + Padding.Top + Padding.Bottom);
				}
			}
		}
	}
}
